package com.haibo.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.haibo.entity.model.BookDO;
import com.haibo.service.BookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author : 刘海波
 * @Date: 2025-08-25 21:09
 * @Description: 【书籍信息】
 */
@Slf4j
@Service
public class BookServiceImpl implements BookService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 查询所有的图书：手动映射，适用于model的字段和数据库表字段不同的情况
     * @return
     */
    @Override
    public List<BookDO> listAllBook() {
        String sql = "select id,create_time,update_time,is_deleted as 'deleted' ,book_name,author from book";
        List<BookDO> bookDOS = jdbcTemplate.query(sql, new RowMapper<BookDO>() {
            @Override
            public BookDO mapRow(ResultSet rs, int rowNum) throws SQLException {
                BookDO bookDO = new BookDO();
                
                Long id = rs.getLong("id");
                bookDO.setId(id);

                Timestamp gmtCreatedTimestamp = rs.getTimestamp("create_time");
                if (ObjectUtil.isNotNull(gmtCreatedTimestamp)) {
                    LocalDateTime createTime = LocalDateTimeUtil.of(gmtCreatedTimestamp.getTime(), ZoneOffset.ofHours(8));
                    bookDO.setCreateTime(createTime);
                }

                Timestamp gmtModifiedTimestamp = rs.getTimestamp("update_time");
                if (ObjectUtil.isNotNull(gmtModifiedTimestamp)) {
                    LocalDateTime updateTime = LocalDateTimeUtil.of(gmtModifiedTimestamp.getTime(), ZoneOffset.ofHours(8));
                    bookDO.setUpdateTime(updateTime);
                }

                Integer deleted = rs.getInt("deleted");
                bookDO.setDeleted(deleted);

                String bookName = rs.getString("book_name");
                bookDO.setBookName(bookName);

                String author = rs.getString("author");
                bookDO.setAuthor(author);
                
                return bookDO;
            }
        });

        return bookDOS;
    }

    /**
     * 查询所有的图书：自动映射，适用于model的字段和数据库表字段一一对应的情况
     * @return
     */
    @Override
    public List<BookDO> selectAllBook() {
        String sql = "select id, create_time as 'createTime', update_time as 'updateTime', is_deleted as 'deleted', book_name as 'bookName', author from book";
        List<BookDO> bookDOS = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(BookDO.class));

        return bookDOS;
    }

    /**
     * 根据ID查询图书
     * @param id
     * @return
     */
    @Override
    public BookDO getById(Long id) {
        String sql = "select id, create_time as 'createTime', update_time as 'updateTime', is_deleted as 'deleted', book_name as 'bookName', author from book where id = ?";
        Object[] args = {id};
        BookDO bookDO = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<BookDO>(BookDO.class), args);

        return bookDO;
    }

    /**
     * 统计记录数
     * @return
     */
    @Override
    public Integer count() {
        String sql = "select count(*) from book";
        Integer result = jdbcTemplate.queryForObject(sql, Integer.class);

        return result;
    }

    /**
     * 添加图书
     * @param bookDO
     * @return
     */
    @Override
    public Integer save(BookDO bookDO) {
        String sql = "insert into book(create_time,book_name,author) values(?,?,?)";

        return jdbcTemplate.update(sql, bookDO.getCreateTime(), bookDO.getBookName(), bookDO.getAuthor());
    }

    /**
     * 批量添加图书
     * @param bookDOS
     * @return
     */
    @Override
    public Integer saveBatch(List<BookDO> bookDOS) {
        String sql = "insert into book(create_time,book_name,author) values(?,?,?)";
        List<Object[]> batchArgs = new ArrayList<>();
        for (BookDO bookDO : bookDOS) {
            Object[] o = new Object[]{bookDO.getCreateTime(),bookDO.getBookName(),bookDO.getAuthor()};
            batchArgs.add(o);
        }
        int[] resultArray = jdbcTemplate.batchUpdate(sql, batchArgs);

        return resultArray.length;
    }

    /**
     * 更新图书
     * @param bookDO
     * @return
     */
    @Override
    public Integer update(BookDO bookDO) {
        String sql = "update book set author = ? where id = ?";
        int num = jdbcTemplate.update(sql, bookDO.getAuthor(), bookDO.getId());

        return num;
    }

    /**
     * 根据ID删除
     * @param id
     * @return
     */
    @Override
    public Integer delById(Long id) {
        String sql = "delete from book where id = ?";
        int num = jdbcTemplate.update(sql,id);

        return num;
    }
}
